<template>
  <div>
    <div class="flex-wrap" v-if="filelist.length>0">
      <img :src="item.url" class="img ml5 mt5" @click="preview(item.url)" v-for="(item,index) in filelist " />
    </div>
    <el-image-viewer v-if="showViewer" :initialIndex="initialIndex" :on-close="closeViewer" :url-list="fileviews"
      :z-index="9999" />
  </div>
</template>
<script>
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
  export default {
    name: "viewfj",
    components: {
      ElImageViewer
    },
    props: {
      value: [String, Object, Array],
      accept: {
        type: String,
        default: () => {
          return ".jpg,.png,.pdf,.doc,.docx,.xls,.xlsx";
        }
      }
    },
    data() {
      return {
        showViewer: false,
        initialIndex: 0,
        filelist: [],
        fileviews: [],
        baseUrl: process.env.VUE_APP_BASE_API,
      }
    },
    mounted() {},
    watch: {
      value: {
        handler(val) {
          if (val) {
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.filelist = list.map(item => {
              if (typeof item === "string") {

                if ((item.indexOf(this.baseUrl) === -1 ) & item.indexOf('http') === -1 ) {
                  item = {
                    name: this.baseUrl + item,
                    url: this.baseUrl + item
                  };
                } else {
                  item = {
                    name: item,
                    url: item
                  };
                }
              }
              return item;
            });

          } else {
            this.filelist = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    },
    activated() {

    },
    methods: {
      getFileExt(fileName) {
        const lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex === -1) {
          return '';
        }
        return fileName.slice(lastDotIndex + 1);
      },
      closeViewer() {
        this.showViewer = false;
      },
      getimg(file) {
        const exts = ["png", "jpg"];
        return exts.indexOf(this.getFileExt(file)) > -1;
      },
      preview(file) {

       let that = this;
       this.fileviews = [];
       this.initialIndex = 0

       this.filelist.forEach(function(item, index, arr) {
         // if (that.getimg(item.url) >= 0) {

         // }
         that.fileviews.push(item.url);
         if (item == file) that.initialIndex = that.fileviews.length - 1;
       })
       if (that.fileviews.length > 0) this.showViewer = true
      }
    }
  }
</script>

<style scoped>
  .img {
    cursor: pointer;
    height: 180px;
    width: 180px;
  }
</style>
